package com.jeasonzhao.commons.parser.expression;

import com.jeasonzhao.commons.utils.Algorithms;
import com.jeasonzhao.commons.utils.DataTypes;

public final class ValuePair
{
    public static final ValuePair NULL=new ValuePair();
    private DataTypes dataType = DataTypes.OBJECT;
    private Object value = null;
    public ValuePair()
    {
        super();
    }

    public ValuePair(Object v)
    {
        super();
        this.value = v;
        if(null != v)
        {
            this.dataType = DataTypes.from(v.getClass());
        }
    }

    public ValuePair(Object value,DataTypes dt)
    {
        super();
        this.value = value;
        setDataType(dt);
    }

    public DataTypes getDataType()
    {
        return dataType;
    }

    public Object getValue()
    {
        return value;
    }

    public void setDataType(DataTypes dataType)
    {
        if(null == dataType)
        {
            this.dataType = DataTypes.OBJECT;
        }
        else
        {
            this.dataType = dataType;
        }
    }

    public void setValue(Object value)
    {
        this.value = value;
    }

    public String toString()
    {
        return Algorithms.toString(this.value);
    }

    public Object getRealData()
        throws ValueCastException
    {
        return getRealData(this.dataType,this.value);
    }

    public Object getRealData(Class<?> cls)
        throws ValueCastException
    {
        return getRealData(null == cls ? dataType : DataTypes.from(cls),this.value);
    }

    public Object getRealData(DataTypes dt)
        throws ValueCastException
    {
        return getRealData(null == dt ? dataType : dt,this.value);
    }

    public static Object getRealData(DataTypes dt,Object value)
        throws ValueCastException
    {
        try
        {
            return dt.castValue(value);
        }
        catch(Exception ex)
        {
            throw new ValueCastException("Cast to " + dt.getInitType().getName() + " error," + ex.getMessage());
        }
    }
}
